import React, { useEffect, useState, useRef } from 'react'
import * as echarts from 'echarts';
// import * as echarts from 'echarts/core';
// import {
//     BarChart,
//     // 系列类型的定义后缀都为 SeriesOption
//     BarSeriesOption,
//     PieChart,
//     PieSeriesOption,
//     LineChart,
//     LineSeriesOption,
//     HeatmapChart,
//     HeatmapSeriesOption
// } from 'echarts/charts';
// import {
//     TitleComponent,
//     // 组件类型的定义后缀都为 ComponentOption
//     TitleComponentOption,
//     TooltipComponent,
//     TooltipComponentOption,
//     GridComponent,
//     GridComponentOption,
//     // 数据集组件
//     DatasetComponent,
//     DatasetComponentOption,
//     LegendComponent,
//     // 内置数据转换器组件 (filter, sort)
//     TransformComponent,
//     CalendarComponentOption,
//     CalendarComponent,
//     VisualMapComponent,
//     VisualMapComponentOption,
//     ToolboxComponent
// } from 'echarts/components';
import { LabelLayout, UniversalTransition } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';
import './EchartCore.less';
import { Spin } from 'antd';
import { FieldNumberOutlined } from '@ant-design/icons';
import { useTranslation } from 'react-i18next';

export type ECOption = echarts.EChartsOption
// 通过 ComposeOption 来组合出一个只有必须组件和图表的 Option 类型
// export type ECOption = echarts.ComposeOption<
//     | BarSeriesOption
//     | LineSeriesOption
//     | TitleComponentOption
//     | TooltipComponentOption
//     | GridComponentOption
//     | DatasetComponentOption
//     | CalendarComponentOption
//     | HeatmapSeriesOption
//     | VisualMapComponentOption
//     | PieSeriesOption
// >;

// // 注册必须的组件
// echarts.use([
//     LegendComponent,
//     TitleComponent,
//     TooltipComponent,
//     GridComponent,
//     DatasetComponent,
//     TransformComponent,
//     CalendarComponent,
//     VisualMapComponent,
//     ToolboxComponent,
//     BarChart,
//     LineChart,
//     PieChart,
//     LabelLayout,
//     HeatmapChart,
//     UniversalTransition,
//     CanvasRenderer
// ]);

interface IProps {
    // option: ECOption
    option: echarts.EChartsOption
    loading?: boolean
    title?: string
    style?: React.CSSProperties
    unit?: string
    data?: {
        xData: any[]
        yData: any[]
    }
    isNoData?: boolean
}

const defaultChartStyle: React.CSSProperties = {
    height: 300
}

// https://echarts.apache.org/handbook/zh/how-to/data/dynamic-data
export default function EchartCore(props: IProps) {
    const [chartInstance, setChartInstance] = useState<echarts.ECharts>()
    const chartRef = useRef<echarts.ECharts>();
    const chartDomRef = useRef<string>(Math.random().toString(36).substring(2));
    const { t, i18n } = useTranslation();
    const resizeTimerRef = useRef<number | null>(null);

    // const option = {} // 移除这个空对象，它会覆盖props.option

    useEffect(() => {
        const chartDom = document.getElementById(chartDomRef.current)
        if (chartDom) {
            // 如果已经初始化过图表，先销毁
            if (chartRef.current) {
                chartRef.current.dispose();
            }

            // 初始化图表
            const chart = echarts.init(chartDom);
            chartRef.current = chart;
            setChartInstance(chart);

            // 使用requestAnimationFrame优化性能
            requestAnimationFrame(() => {
                chart.setOption(props.option);
            });

            // 处理窗口resize事件
            const handleResize = () => {
                // 使用防抖处理resize事件
                if (resizeTimerRef.current !== null) {
                    window.cancelAnimationFrame(resizeTimerRef.current);
                }
                
                resizeTimerRef.current = window.requestAnimationFrame(() => {
                    if (chart && !chart.isDisposed()) {
                        chart.resize();
                    }
                    resizeTimerRef.current = null;
                });
            };

            window.addEventListener('resize', handleResize);

            // 组件卸载时清理事件监听和echarts实例
            return () => {
                window.removeEventListener('resize', handleResize);
                if (resizeTimerRef.current !== null) {
                    window.cancelAnimationFrame(resizeTimerRef.current);
                }
                if (chart && !chart.isDisposed()) {
                    chart.dispose();
                }
            };
        }
    }, []);

    // 当props.option或props.data变化时更新图表
    useEffect(() => {
        if (chartRef.current && !chartRef.current.isDisposed()) {
            // 使用requestAnimationFrame优化性能
            requestAnimationFrame(() => {
                chartRef.current!.setOption(props.option);
            });
        }
    }, [props.option, props.data]);

    return (
        <Spin spinning={props.loading}>
            <div className="chart-container">
                <div id={chartDomRef.current} style={{ ...defaultChartStyle, ...props.style }}></div>
                {
                    props.isNoData ? <div className="chart-nodata">
                        <div>{t('暂无数据')}</div>
                    </div> : null
                }
            </div>
        </Spin>
    )
}
